#include <QDebug>

#include "net_queue.h"

NetQueue::NetQueue (int latency, int throughput)
  : _latency (latency), _packet_size (latency * throughput)
{
  connect (&_timer, SIGNAL (timeout ()), SLOT (timeout ()));
}

void NetQueue::clear ()
{
  _timer.stop ();
  _queue.clear ();
}

void NetQueue::queue_data (const QByteArray& data)
{
  _queue.append (data);

  if (!_timer.isActive ())
    _timer.start (_latency);
}

void NetQueue::timeout ()
{
  if (_queue.size () == 0) {
    qDebug ()
      << "Something went wrong, got a timeout with nothing in the queue";
    return;
  }

  QByteArray d = _queue.mid (0, _packet_size);
  _queue.remove (0, _packet_size);
  qDebug () << "Sending" << d.size () << "bytes" << _queue.size () << "left";

  data_ready (d);

  if (_queue.size () == 0)
    _timer.stop ();
}
